package com.atguigu.gmall.activity.receiver;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import com.atguigu.gmall.activity.mapper.SeckillGoodsMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Component
public class SeckillReceiver {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TASK_1),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_TASK),
            key = {MqConst.ROUTING_TASK_1}
    ))
    public void importItemToRedis(Message message, Channel channel) throws IOException {
        QueryWrapper<SeckillGoods> seckillGoodsQueryWrapper = new QueryWrapper<>();
        seckillGoodsQueryWrapper.eq("status",1)
                .eq("DATE_FORMAT(start_time,'%Y-%m-%d')", DateUtil.formatDate(new Date()))
                .gt("stock_count",0);
        try {
            List<SeckillGoods> seckillGoodList = seckillGoodsMapper.selectList(seckillGoodsQueryWrapper);
            if (!CollectionUtils.isEmpty(seckillGoodList)) {
                for (SeckillGoods seckillGoods : seckillGoodList) {
                    //查看缓存中是否有已存在的sku
                    Boolean flag = redisTemplate.boundHashOps(RedisConst.SECKILL_GOODS).hasKey(seckillGoods.getSkuId());
                    if (flag){
                        //如果缓存已存在 sku 则跳出循环，防止缓存中的库存数据重复保存
                        continue;
                    }
                    redisTemplate.boundHashOps(RedisConst.SECKILL_GOODS).put(seckillGoods.getSkuId(),seckillGoods);
                    //根据每一个seckillGoods商品的数量把商品按队列的形式放进redis中
                    for (Integer i = 0; i < seckillGoods.getStockCount(); i++) {
                        redisTemplate.boundListOps(RedisConst.SECKILL_STOCK_PREFIX+seckillGoods.getSkuId())
                                .leftPush(seckillGoods.getSkuId().toString());
                    }
                                /*
                                 消息格式
                                    skuId:0 表示没有商品
                                    skuId:1 表示有商品
                                 */
                     redisTemplate.convertAndSend("seckillpush", seckillGoods.getSkuId()+":1");
                }

                // 手动确认接收消息成功
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            }
        } catch (IOException e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            e.printStackTrace();
        }

    }
}